/*
 * @File    :   main.js
 * @Time    :   2024/03/24 17:14:21
 * @Author  :   chakcy
 * @Email   :   947105045@qq.com
 * @description   :   main.js
 */

const { app, Notification, Menu, dialog } = require("electron")

// 引入自定义模块
const { WindowManager, IpcHandler, menu } = require('./modules')
const { pool } = require('./common')
const { basePath, render } = require('./config')
const { spawn } = require('child_process')

const path = require('path')

// 启动 socket 服务
let socketProcess = null

// 关闭 socket 服务
function closeSocketProcess(process) {
    console.log('Closing Socket server')
    if (process.stdin && process.stdin.writable) {
        process.stdin.write('shutdown\n');
    }
    process.on('close', (code) => {
        console.log(`Python server closed with code ${code}`);
    });
}

// 应用程序准备就绪时
app.on('ready', () => {
    // 菜单栏
    let m = Menu.buildFromTemplate(menu)
    Menu.setApplicationMenu(m)

    // 创建窗口管理器实例
    const manager = new WindowManager()

    // 创建窗口
    const { win } = manager.createWindow(render)
    // 实例化IPC处理程序
    new IpcHandler()
})

// 应用程序准备退出前
app.on('before-quit', () => {
    // 关闭所有池
    pool.closeAll()
    closeSocketProcess(socketProcess)
})

// 当所有窗口关闭时触发
app.on('window-all-closed', () => {
    // 如果不是在 macOS 平台上运行，则退出应用
    if (process.platform !== 'darwin') app.quit()
    closeSocketProcess(socketProcess)

})

app.on('will-finish-launching', () => {
    socketProcess = spawn(path.join(basePath, "..\\dist\\main.exe"), [])
})
